﻿using FlyingEye.Common.Utils;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.DependencyInjection;

namespace FlyingEye.Extensions
{
    public static class KestrelExtensions
    {
        public static WebApplicationBuilder ConfigureKestrel(this WebApplicationBuilder builder)
        {
            var provider = builder.Services.BuildServiceProvider();
            var applicationConfiguration = provider.GetRequiredService<ApplicationConfiguration>();
            var configuration = applicationConfiguration.GetCertificateAuthorityCertificate();

            builder.WebHost.UseKestrel(serverOptions =>
            {
                // 配置端口监听和证书。
                serverOptions.ListenAnyIP(configuration.Port, listeningOptions =>
                {
                    listeningOptions.UseHttps(configuration.X509Certificate, options =>
                    {
#if DEBUG 
                        // 调试模式下，启动任意认证。
                        options.AllowAnyClientCertificate();
#endif
                    });
                });

                // 配置使用 TLS 协议。
                serverOptions.ConfigureHttpsDefaults(options =>
                {
                    options.SslProtocols = System.Security.Authentication.SslProtocols.Tls13
                    | System.Security.Authentication.SslProtocols.Tls12
                    | System.Security.Authentication.SslProtocols.Tls11
                    | System.Security.Authentication.SslProtocols.Tls;
                });
            });

            return builder;
        }
    }
}
